package cn.edu.ecnu.gis.client.gadgets;

import cn.edu.ecnu.gis.client.ltapi.localsearch.LTLocalSearchRequest;
import cn.edu.ecnu.gis.client.ltapi.localsearch.LTLocalSearchRequestHandle;
import cn.edu.ecnu.gis.client.model.Gadget;
import cn.edu.ecnu.gis.client.model.GadgetClass;
import cn.edu.ecnu.gis.client.view.FiveOneMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ImageBundle;

public class FiveOneMapsGadget extends Gadget implements LTLocalSearchRequestHandle {

    public static class Class extends GadgetClass {

        public Class() {
            super("51地图", false);
            this.setGadgetType(1);
        }

        public Gadget newGadget() {
            return new FiveOneMapsGadget(this);
        }
    }
    private FiveOneMap map = new FiveOneMap();

    public FiveOneMap getLTMap() {
        return map;
    }

    protected FiveOneMapsGadget(Class c) {
        super(c);
        initWidget(map);
        map.setCenter("shanghai", 2);
        map.addControl();

    }

    public void refresh() {
//		list.clear();
//		String url = (String) getUserPrefValue( Class.feed );
        LTLocalSearchRequest.search("中山北路3663号", "上海", this);
    }

    public void refresh(String address) {
        LTLocalSearchRequest.search(address, "上海", this);
    }

    public void onRequestComplete(String result) {
        JSONObject searchResult = (JSONObject) JSONParser.parse(result);
        //JSONArray entries = (JSONArray) searchResult.get("entries");
        JSONArray searchPoints = (JSONArray) searchResult.get("searchPoints");

        //for (int i = 0; i < searchPoints.size(); i++) {
            JSONObject item = (JSONObject) searchPoints.get(0);
            JSONString id = (JSONString) item.get("id");
            JSONString url = (JSONString) item.get("url");
            JSONString name = (JSONString) item.get("name");
            JSONArray points = (JSONArray) item.get("point");
            map.addMarker(points);
            HTML html = new HTML("<a href='" + url.stringValue() + "' target='_blank'>" + name.stringValue() + "</a>");
            html.setStyleName("News-Item");
        //list.add( html );
       // }
    }

    public void onRequestFailed(String error) {
        HTML html = new HTML(" error ");
        html.setStyleName("News-Item");
    }

    public interface BoundImage extends ImageBundle {

        AbstractImagePrototype inbox();
    }

    public AbstractImagePrototype getBoundImage() {
        BoundImage images = (BoundImage) GWT.create(BoundImage.class);
        return images.inbox();
    }
}
